package spark.network.protocol;

import spark.network.Util;

public class ClockSyncRes extends Response<ClockSyncReq> {
	private static final Class<ClockSyncReq> REQUEST_TYPE_CLASS = ClockSyncReq.class;

	public static final short TYPE = 0x05;
	private static final byte[] TYPE_BYTES = Util.makeBytes(TYPE);

	private long localTime;
	private static final int LOCAL_TIME_OFFSET = Response.SIZE;
	private static final int LOCAL_TIME_LENGTH = Long.SIZE / 8;

	private static final int SIZE =
			Response.SIZE +
			LOCAL_TIME_LENGTH;

	public ClockSyncRes() {
		super(false, TYPE_BYTES, REQUEST_TYPE_CLASS);
	}

	public ClockSyncRes(ClockSyncReq query) {
		super(false, TYPE_BYTES, query, REQUEST_TYPE_CLASS);
	}

	public long getLocalTime() {
		return localTime;
	}

	public void setLocalTime(long localTime) {
		this.localTime = localTime;
	}

	@Override
	public int getSize() {
		return SIZE;
	}

	@Override
	public void fill(byte[] buffer) {
		super.fill(buffer);
		localTime = Util.makeLong(buffer, LOCAL_TIME_OFFSET);
	}

	@Override
	public void getBytes(byte[] buffer) {
		super.getBytes(buffer);
		Util.arraycopy(Util.makeBytes(localTime), 0, buffer, LOCAL_TIME_OFFSET);
	}

	public static ClockSyncRes create(byte[] buffer, long receiveTime) {
		ClockSyncRes packet = new ClockSyncRes();
		packet.fill(buffer);
		packet.setTimeStampReceive(receiveTime);
		return packet;
	}
}